#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "insam_func.h"
#include "packet.h"

int login_process(BYTE *msg, struct sockaddr_in *client) {
	printf("Start Login process.. >");

	REQ_LOGIN p_login;
	char id[UID_LEN+1], passwd[PASSWD_LEN+1], *os=NULL;
	memcpy(&p_login, msg, sizeof(p_login));
	memcpy(id, p_login.uid, UID_LEN);
	memcpy(passwd, p_login.passwd, PASSWD_LEN);
	id[UID_LEN] = 0;
	passwd[PASSWD_LEN] = 0;
	int rtn=-1;

	printf("id:%s, passwd:%s\n", id, passwd);

	if(connectDB()< 0) {
		printLog(client, "connet db failed!!");
		msg[0] = -1;
		return 1;
	}

	if((rtn=verifyUser(id, passwd))<0) {
		if(rtn==-2) {
			printLog(client, "Invalid Id!!(%s)", id);
		} else if(rtn==-3) {
			printLog(client, "Wrong password!!(%s)", id);
		}
		msg[0] = rtn;
		printf("rtn:%d\n", msg[0]);
		return 1;
	}

	short port;
	if((port=checkPort(id))==0) {
		port = allocatePort(id, inet_ntoa(client->sin_addr));
	}

	if(port <= 0) {
		msg[0] = -1;
		return 1;
	}

	os = getOS(id);
	if(os==NULL) {
		msg[0] = -1;
		return 1;
	}


	closeDB();

	char fileName[MAXBUFF_LEN];
	sprintf(fileName, "/media/BOOTCAMP/insam-image/%s-%s.insam", id, os);
	char strPort[3];
	sprintf(strPort,":%d",port);
	printLog(client, "execute %s", fileName);
	pid_t pid = fork();
	if(pid == 0)
	{
		execlp("qemu","qemu", fileName,"-m","256","-vnc", strPort, "-full-screen", "-net", "none",  NULL);

		//화면크기 추가로 넣어주기,  "-serial", "vc:1024x768"
		//인터넷 안되게 하기, 패스워드 넣기
		//오류나면 화면 받아오기(pipe 사용)
		//
		printLog(client, "end vnc connection(%s)", id);
		freePort(id);
	}

	port+=5900;
	printf("send port:%d\n", port);
	port = htons(port);
	msg[0] = 1;
	memcpy(msg+1, &port, sizeof(port));

	return 1 + sizeof(port);
}
